<template>
  <div class="user-data-container">
    <!-- user-data-header -->
    <div class="user-data-header">
      <el-button type="primary" icon="el-icon-plus" @click.stop="handleAdd"
        >新建</el-button
      >
      <el-input
        placeholder="请输入内容"
        v-model="reqPage.keyword"
        :style="{ width: '300px' }"
        @keyup.enter="getUserListData"
      >
        <el-button @click.stop="getUserListData" slot="append">搜索</el-button>
      </el-input>
    </div>

    <!-- 表格数据展示 -->
    <div class="user-data-table">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="username" label="账号" width="100">
        </el-table-column>
        <el-table-column
          show-overflow-tooltip
          prop="password"
          label="密码"
          width="100"
        >
        </el-table-column>
        <el-table-column prop="real_name" label="真实姓名" width="100" />
        <el-table-column prop="mobile" label="联系电话" width="180" />
        <el-table-column label="用户类型" width="100">
          <template slot-scope="scope">
            <span>{{
              { street: '街道', community: '社区' }[scope.row.user_type]
            }}</span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip label="管辖区域">
          <template slot-scope="scope">
            <span>{{ scope.row.monitoring_community | filterCommunity }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" @click.stop="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="text"
              class="del-btn"
              @click.stop="handleDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-box">
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="reqPage.page_size"
        :total="reqPage.page_total"
        @current-change="currentChange"
      >
      </el-pagination>
    </div>

    <!-- 新建&编辑弹窗 -->
    <el-dialog
      :visible.sync="userDialog"
      @open="onOpen"
      @close="onClose"
      :close-on-click-modal="false"
      :title="title"
    >
      <el-row :gutter="15">
        <el-form
          ref="elForm"
          :model="formData"
          :rules="rules"
          size="small"
          label-width="100px"
          label-position="top"
        >
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input
                v-model="formData.username"
                placeholder="请输入设施账号"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="formData.password"
                type="password"
                placeholder="请输入密码"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="真实姓名" prop="real_name">
              <el-input
                v-model="formData.real_name"
                placeholder="请输入真实姓名"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="mobile">
              <el-input
                v-model="formData.mobile"
                placeholder="请输入联系方式"
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="user_type">
              <el-input
                v-model="formData.user_type"
                placeholder="请输入用户类型"
                readonly
                clearable
                :style="{ width: '100%' }"
              >
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管辖区域" prop="monitoring_community">
              <el-cascader
                collapse-tags
                v-model="formData.monitoring_community"
                :options="field109Options"
                :props="field109Props"
                :style="{ width: '100%' }"
                placeholder="请输入管辖区域"
                filterable
                clearable
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCommunityCascaderList,
  addUser,
  editUser,
  deleteUser,
  getUserList,
} from '@/api/user-manager'

import md5 from 'js-md5'
export default {
  name: 'user-data',
  filters: {
    filterCommunity(arr) {
      if (arr) {
        let newArr = JSON.parse(JSON.stringify(arr))

        return newArr
          .map((item) => {
            return item.join(' » ')
          })
          .join(', ')
      }
    },
  },
  data() {
    return {
      title: '新增',
      reqPage: {
        keyword: '',
        user_type: '',
        page_size: 10,
        page_index: 1,
        page_total: 0,
      },
      userDialog: false,
      tableData: [],
      formData: {
        username: undefined,
        password: undefined,
        real_name: undefined,
        mobile: undefined,
        user_type: undefined,
        monitoring_community: [[1, 2]],
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入设施账号',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
          },
        ],
        mobile: [
          {
            required: true,
            message: '请输入联系方式',
            trigger: 'blur',
          },
          {
            pattern: /^1[3456789]\d{9}$/,
            message: '请正确输入联系方式',
            trigger: 'blur',
          },
        ],
        user_type: [
          {
            required: true,
            message: '请输入用户类型',
            trigger: 'blur',
          },
        ],
        monitoring_community: [
          {
            required: true,
            type: 'array',
            message: '请至少选择一个管辖区域',
            trigger: 'change',
          },
        ],
      },
      field109Options: [],
      field109Props: {
        multiple: true,
        label: 'label',
        value: 'value',
        children: 'children',
        checkStrictly: false,
      },
    }
  },
  created() {
    getCommunityCascaderList({ type: 'admin' }).then((res) => {
      if (res.meta.successful) {
        this.field109Options = res.data
      }
    })
    this.formData.user_type = 'street'
    this.reqPage.user_type = 'street'

    this.getUserListData()
  },
  methods: {
    currentChange(page) {
      this.reqPage.page_index = page
      this.getUserListData()
    },
    // 新增
    handleAdd() {
      this.title = '新增'
      this.userDialog = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
        this.formData.id = ''
      })
    },
    // 类型控制
    getListByType(type) {
      this.formData.user_type = type
      this.reqPage.user_type = type
      this.getUserListData()
    },
    // 获取用户列表
    getUserListData() {
      getUserList(this.reqPage).then((res) => {
        if (res.meta.successful) {
          this.tableData = res.data.page_data.map((item) => {
            if (
              item.monitoring_community &&
              typeof item.monitoring_community === 'string'
            )
              item.monitoring_community = JSON.parse(item.monitoring_community)
            return item
          })
          this.reqPage.page_total = res.data.record_count
        }
      })
    },
    onOpen() {},
    onClose() {
      this.$refs['elForm'].resetFields()
      this.formData.id = ''
    },
    close() {
      this.$emit('update:visible', false)
    },
    handelConfirm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return false
        let newFormData = JSON.parse(JSON.stringify(this.formData))
        // 加密密码
        newFormData.password = md5(newFormData.password)
        console.log(newFormData)
        if (newFormData.id) {
          editUser(newFormData).then((res) => {
            if (res.meta.successful) {
              this.$message.success('修改成功！')
              this.getUserListData()
              this.userDialog = false
            } else {
              this.$message.info(res.meta.message)
            }
          })
        } else {
          addUser(newFormData).then((res) => {
            if (res.meta.successful) {
              this.$message.success('新建成功！')
              this.getUserListData()
              this.userDialog = false
            } else {
              this.$message.info(res.meta.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          deleteUser({ id: row.id }).then((res) => {
            if (res.meta.successful) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.getUserListData()
            }
          })
        })
        .catch(() => {})
    },
    handleEdit(row) {
      this.title = '编辑'
      this.formData = JSON.parse(JSON.stringify(row))
      this.userDialog = true
      console.log(row)
    },
  },
}
</script>

<style lang="scss">
.user-data-container {
  padding: 20px;
  background: white;
  height: 100%;
  box-sizing: border-box;
  .el-dialog__header {
    background: #3da1d2;
    color: white;
    .el-dialog__title {
      color: white;
    }
    .el-dialog__headerbtn .el-dialog__close {
      color: white;
    }
  }
  .user-data-header {
    display: flex;
    justify-content: space-between;
  }
  .user-data-table {
    margin-top: 20px;
    .el-table th {
      background: #f1f4f9;
    }

    .del-btn {
      span {
        color: #fe7372;
      }
    }
  }
  .page-box {
    padding: 20px;
    text-align: right;
  }
}
</style>
